package SimilarAlgorithm;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import ParticiplePkg.Participle;
import ParticiplePkg.SimpleParticiple;

public class TextSimiarity implements Similarity<String>{
	private Participle pcp;
	public TextSimiarity(){
		this.pcp=new SimpleParticiple();
	}
	public TextSimiarity(Participle pcp){
		this.pcp=pcp;
	}
	public  double getSimilarity(String doc1, String doc2) {

		
		Map<String, int[]> AlgorithmMap = new HashMap<String, int[]>();
		
		String[] doc1Arr=pcp.participle(doc1);
		//将两个字符串中的中文字符以及出现的总数封装到，AlgorithmMap中
		for (int i = 0; i < doc1Arr.length; i++) {
			String d1 = doc1Arr[i];
			int[] fq = AlgorithmMap.get(d1);
			if(fq != null && fq.length == 2){
				fq[0]++;
			}else {
				fq = new int[2];
				fq[0] = 1;
				fq[1] = 0;
				AlgorithmMap.put(d1, fq);
			}
		}
		String[] doc2Arr=pcp.participle(doc2);
		for (int i = 0; i < doc2Arr.length; i++) {
			String d2 = doc2Arr[i];
			int[] fq = AlgorithmMap.get(d2);
			if(fq != null && fq.length == 2){
				fq[1]++;
			}else {
				fq = new int[2];
				fq[0] = 0;
				fq[1] = 1;
				AlgorithmMap.put(d2, fq);
			}
		}
		
		Iterator<String> iterator = AlgorithmMap.keySet().iterator();
		double sqdoc1 = 0;
		double sqdoc2 = 0;
		double denominator = 0; 
		while(iterator.hasNext()){
			String key=iterator.next();
			System.out.println("key: "+key);
			int[] c = AlgorithmMap.get(key);
			denominator += c[0]*c[1];
			sqdoc1 += c[0]*c[0];
			sqdoc2 += c[1]*c[1];
		}
		
		return denominator / Math.sqrt(sqdoc1*sqdoc2);
	
	}

}
